package com.pomr.service.sys.Impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import com.pomr.entity.UserEffect;
import com.pomr.model.sys.Effect;
import com.pomr.util.common.CommonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.sys.UerDao;
import com.pomr.model.sys.User;
import com.pomr.service.sys.LoginService;
import com.pomr.util.common.MD5;
@Service
public class LoginServiceImpl implements LoginService {
	@Autowired
	@Qualifier("uerDaoImpl")
	private UerDao uerDao;

	@Override
	public User getUserOfLogin(User user) throws Exception {
		user.setPassword(MD5.encodeByMd5(user.getPassword()));//对密码进行md5加密
		user = uerDao.getUserOfLogin(user);
		return user;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean registerUser(User user) throws Exception {
		user.setPassword(MD5.encodeByMd5(user.getPassword()));//对密码进行md5加密
		return uerDao.add(user);
	}

	@Override
	public boolean testUname(String uname) throws Exception {
		List<User> users = uerDao.findByHql("from User where uname='"+uname+"'");
		if(users==null || users.size()<=0){
			return false;
		}
		return true;
	}

	@Override
	public boolean testUnameByEmail(String uname, String email) throws Exception {
		List<User> users = uerDao.findByHql("from User where uname='"+uname+"' and email='"+email+"'");
		if(users==null || users.size()<=0){
			return false;
		}
		return true;
	}

	@Override
	public boolean changePwd(String uname, String pwd) throws Exception {
		int changerow = uerDao.editNumHql("update User set password='"+MD5.encodeByMd5(pwd)+"' where uname='"+uname+"'");
		if(changerow <= 0){
			return false;
		}
		return true;
	}

	@Override
	public UserEffect searchEffectsByUserId(Integer userid) throws Exception {
		System.err.println("加载菜单信息");
		UserEffect userEffect = new UserEffect();
		userEffect.setUser(null);
		userEffect.setRole(null);
		List<Effect> effects = uerDao.findBySql("select * from effect where id in (select effect_id from role_effect where role_id=(select type from user where id="+userid+")) and patient_id is null", Effect.class);
		for(Effect effect:effects){
			String sql = "select * from effect where id in (select effect_id from role_effect where role_id=(select type from user where id="+userid+")) and patient_id = "+effect.getId();
			List<Effect> es = uerDao.findBySql(sql, Effect.class);
			effect.setChilds(new HashSet<Effect>(es));
		}
		userEffect.setEffects(effects);
		return userEffect;
	}
}
